package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/19  14:38
 * @description：TODO
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    //校验登录
    @Override
    public UserInfo login(UserInfo userInfo) {
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("login_name",userInfo.getLoginName());
        queryWrapper.eq("passwd", MD5.encrypt(userInfo.getPasswd()));
        return userInfoMapper.selectOne(queryWrapper);
    }
    //注册
    @Override
    public void register(UserInfo userInfo) {
        String phoneNum = userInfo.getPhoneNum();
        String loginName = userInfo.getLoginName();
        String passwd = userInfo.getPasswd();
        String name = userInfo.getName();
        String email = userInfo.getEmail();
        String nickName = userInfo.getNickName();
        if(StringUtils.isEmpty(phoneNum)||StringUtils.isEmpty(loginName)||
                StringUtils.isEmpty(passwd)||StringUtils.isEmpty(email)||
        StringUtils.isEmpty(nickName)||StringUtils.isEmpty(name)){
            throw new GmallException("注册信息缺失",20001);
        }
        //验证手机号是否存在
        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone_num",phoneNum);
        //统计查询结果
        Integer count = userInfoMapper.selectCount(queryWrapper);
        if(count>0){
            throw new GmallException("该手机号已经注册",20001);
        }
        //MD5加密密码,生成密文
        String encryptPassword = MD5.encrypt(passwd);
        userInfo.setPasswd(encryptPassword);

        userInfoMapper.insert(userInfo);
    }
}
